import "dart:convert";

import "package:ct_pa_majordomo/config/theme_config.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/transfer_station.dart";
import "package:ct_pa_majordomo/pages/user/api.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/router/routes.dart";
import "package:ct_pa_majordomo/state/common.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/utils/storage.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:flutter_localizations/flutter_localizations.dart";
import "package:provider/provider.dart";


class App extends StatelessWidget {
  const App({super.key});

  void getInfo() async {
    Map resData = await userApi.getInfo();
    if (resData["user"] != null) {
      storage.setString("info", jsonEncode(resData["user"]));
    }
  }

  String? routeBeforeHook (RouteSettings settings) {
    String token = storage.getString("token") ?? "";
    String apartment = storage.getString("apartment") ?? "";
    String info = storage.getString("info") ?? "";
    if (token.isNotEmpty) {
      if (info.isEmpty) {
        getInfo();
      }
      if (settings.name == Keys.LOGIN) {
        return Keys.MAIN;
      } else {
        if (apartment.isEmpty) {
          return Keys.CREATE_APARTMENT;
        }

      }
      return settings.name;
    }
    return Keys.LOGIN;
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (ctx) => CommonState()),
      ],
      child: MaterialApp(
        localizationsDelegates: GlobalMaterialLocalizations.delegates,
        navigatorKey: Stacker.key,
        theme: getThemeConfig(context),
        supportedLocales: const [Locale("zh", "CN")],
        home: const TransferStation(),
        builder: EasyLoading.init(),
        // navigatorObservers: [RouterInterceptor()],
        // routes: Routes.getRoutes(context),
        onGenerateRoute: (settings) {
          final String? name = routeBeforeHook(settings);
          // 获取命名路由
          final Function? pageContentBuilder = Routes.getRoutes(context)[name];
          if (pageContentBuilder != null) {
            // 判断路由是否携带参数
            if (settings.arguments != null) {
              return CupertinoPageRoute(
                settings: RouteSettings(name: name, arguments: settings.arguments),
                builder: (context) => pageContentBuilder(context, arguments: settings.arguments),
              );
            } else {
              return CupertinoPageRoute(
                settings: RouteSettings(name: name),
                builder: (context) => pageContentBuilder(context),
              );
            }
          }
          return null;
        },
      ),
    );
  }
}
